<template>
    <div class="article-list">
        <van-pull-refresh
        v-model="isrefreshLoading"
        @refresh="onRefresh"
        :success-text="refreshSuccessText"
        :success-duration="1500">
            <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
            :error.sync="error"
            error-text="请求失败，点击重新加载"
            >
                <ArticleItem v-for="(article,i) in list" :key="i" :article="article" />
            </van-list>
        </van-pull-refresh>
    </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item'

export default {
    name: 'ArticleList',
    props: ['channel'],
    components: {
        ArticleItem
    },
    data () {
        return {
            list: [],
            loading: false,
            finished: false,
            timestamp: null,
            error: false,
            isrefreshLoading: false,
            refreshSuccessText: '刷新成功'
        }
    },
    methods: {
        async onLoad () {
            try {
                const res = await getArticles({
                    channel_id: this.channel.id,
                    timestamp: this.timestamp || Date.now(), // 请求的时间戳，用做页码
                    with_top: 1 // 0表示不包含置顶，1表示包含置顶
                })

                // 获取每次请求到的结果插入list
                const { results } = res.data.data
                this.list.push(...results)

                this.loading = false

                // 如果本次请求的结果长度为0，表示list已到达末尾
                if (results.length) {
                    this.timestamp = res.data.data.pre_timestamp
                } else {
                    this.finished = true
                }
            } catch (err) {
                // 展示错误提示状态
                this.error = true
                this.loading = false
            }
        },
        async onRefresh () {
            try {
                const res = await getArticles({
                    channel_id: this.channel.id,
                    timestamp: Date.now(),
                    with_top: 1
                })

                const { results } = res.data.data
                this.list.unshift(...results)

                this.isrefreshLoading = false
                this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`
            } catch (err) {
                this.isrefreshLoading = false
                this.refreshSuccessText = '刷新失败'
            }
        }
    }
}
</script>

<style scoped>
.article-list {
    /* 使滚动容器变为每个独立的列表，而不是整个body */
    height: 72vh;
    overflow-y: auto;
}
</style>
